package com.brainstrongtech.bfs.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class EncodingFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		String method = request.getMethod();
		// System.out.println("method = " + method);
		if (method.equals("POST")) {
			request.setCharacterEncoding("UTF-8");
		} else {
			// GET请求，需求对GET请求的参数进行转码的处理。
			request = new MyRequestWrapper(request);
		}

		response.setCharacterEncoding("UTF-8");

		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	class MyRequestWrapper extends HttpServletRequestWrapper {
		public MyRequestWrapper(HttpServletRequest request) {
			super(request);
		}

		@Override
		public String getParameter(String name) {
			// System.out.println("重写getParameter方法...");
			if (name != null && !name.equals("")) {
				String old_value = super.getParameter(name);
				String new_value = "";
				if (old_value != null && !old_value.equals("")) {
					try {
						new_value = new String(old_value.getBytes("ISO-8859-1"), "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}

					return new_value;
				}
			}
			return super.getParameter(name);
		}

		@Override
		public String[] getParameterValues(String name) {
			if (name != null && !name.equals("")) {
				String[] old_valueArray = super.getParameterValues(name);
				String[] new_valueArray = null;
				if (old_valueArray != null && old_valueArray.length > 0) {
					new_valueArray = new String[old_valueArray.length];
					for (int i = 0; i < old_valueArray.length; i++) {
						String str = old_valueArray[i];
						String temp_str = "";
						try {
							temp_str = new String(str.getBytes("ISO-8859-1"), "UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}

						new_valueArray[i] = temp_str;
					}
					return new_valueArray;
				}
			}
			return super.getParameterValues(name);
		}
	}
}
